/**
 * Copyright 2014  XCL-Charts
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @Project XCL-Charts
 * @Description Android图表基类库
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 * @Copyright Copyright (c) 2014 XCL-Charts (www.xclcharts.com)
 * @license http://www.apache.org/licenses/  Apache v2 License
 * @version 1.0
 */
package com.demo.xclcharts.view1

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import com.gitee.wsl.common.chart.ChartEnum
import com.gitee.wsl.common.draw.gesture.ZoomType
import com.gitee.wsl.common.chart.sample.bar.BarChart3D
import com.gitee.wsl.common.chart.sample.bar.model.BarData
import com.gitee.wsl.common.ui.draw.type.HorizontalAlign

import java.text.DecimalFormat
import java.util.LinkedList

/**
 * @ClassName Bar3DChart01View
 * @Description  3D柱形图例子
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 */
class BarChart3D01View : DemoView {
    private val TAG = "Bar3DChart01View"
    private val chart = BarChart3D()

    //标签轴
    private val chartLabels: MutableList<String> = LinkedList()

    //数据轴
    private val BarDataset: MutableList<BarData> = LinkedList()
    var mPaintToolTip = Paint(Paint.ANTI_ALIAS_FLAG)

    constructor(context: Context) : super(context) {
        // TODO Auto-generated constructor stub				
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView()
    }

    private fun initView() {
        chartLabels()
        chartDataSet()
        chartRender()

        //綁定手势滑动事件
        this.bindTouch(this, chart)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //图所占范围大小
        //chart.setChartRange(w.toFloat(), h.toFloat())
    }

    private fun chartRender() {
        try {

            //设置绘图区默认缩进px值,留置空间显示Axis,Axistitle....	
            val ltrb = barLnDefaultSpadding
            /*chart.setPadding(
                DensityUtil.dip2px(context, 50f).toFloat(), ltrb[1].toFloat(),
                ltrb[2].toFloat(), (ltrb[3] + DensityUtil.dip2px(context, 25f)).toFloat()
            )*/

            //显示边框
            chart.showRoundBorder()



            //数据源			
            chart.dataSet = BarDataset
            chart.setCategories(chartLabels)

            //坐标系
            chart.dataAxis.axisMax=500.0f
            chart.dataAxis.axisMin=100.0f
            chart.dataAxis.axisSteps = 100.0f
            //chart.getCategoryAxis().setAxisTickLabelsRotateAngle(-45f);

            //隐藏轴线和tick
            chart.dataAxis.hideAxisLine()
            //chart.getDataAxis().setTickMarksVisible(false);

            //标题
            chart.setTitle("本周水果销售情况","(XCL-Charts Demo)")

            chart.setTitleAlign(HorizontalAlign.RIGHT)


            //背景网格
            chart.plotGrid.showHorizontalLines()
            chart.plotGrid.showVerticalLines()
            chart.plotGrid.showEvenRowBgColor()
            chart.plotGrid.showOddRowBgColor()


            //定义数据轴标签显示格式		
            chart.dataAxis.tickLabelRotateAngle = -45f
            chart.dataAxis.tickMarkPaint.color = Color.rgb(186, 20, 26)
            chart.dataAxis.labelFormatter= { value -> // TODO Auto-generated method stub
                val tmp = value.toDouble()
                val df = DecimalFormat("#0")
                val label = df.format(tmp).toString()
                label + "公斤"
            }

            //设置标签轴标签交错换行显示
            chart.categoryAxis.labelLineFeed=(ChartEnum.LabelLineFeed.EVEN_ODD)

            //定义标签轴标签显示格式
            chart.categoryAxis.labelFormatter= { value -> // TODO Auto-generated method stub
                value
            }
            //定义柱形上标签显示格式
            chart.getBar().isShowItemLabel=true
            chart.itemLabelFormatter= { value -> // TODO Auto-generated method stub
                val df = DecimalFormat("#0.00")
                df.format(value).toString()
            }

            //激活点击监听
            //chart.ableSelect()

            //仅能横向移动
            chart.zoomType = ZoomType.HORIZONTAL


            //扩展横向显示范围
            //	chart.getPlotArea().extWidth(200f);

            //标签文字与轴间距
            chart.categoryAxis.tickLabelMargin = 5f

            //不使用精确计算，忽略Java计算误差
            //chart.disableHighPrecision()

            // 设置轴标签字体大小
            chart.dataAxis.tickLabelPaint.textSize = 26f
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
    }

    private fun chartDataSet() {
        //标签对应的柱形数据集
        val dataSeriesA: MutableList<Float> = LinkedList()
        dataSeriesA.add(200.0f)
        dataSeriesA.add(250.0f)
        dataSeriesA.add(400.0f)
        dataSeriesA.add(450.0f)
        dataSeriesA.add(150.0f)
        val dataSeriesB: MutableList<Float> = LinkedList()
        dataSeriesB.add(300.0f)
        dataSeriesB.add(150.0f)
        dataSeriesB.add(450.0f)
        dataSeriesB.add(480.0f)
        dataSeriesB.add(200.0f)
        BarDataset.add(BarData("左边店", dataSeriesA, Color.rgb(252, 210, 9)))
        BarDataset.add(BarData("右边店", dataSeriesB, Color.rgb(55, 144, 206)))
        val dataSeriesC: MutableList<Float> = LinkedList()
        dataSeriesC.add(270.0f)
        dataSeriesC.add(180.0f)
        //dataSeriesC.add(450d); 
        //dataSeriesC.add(380d); 
        //dataSeriesC.add(230d);
        BarDataset.add(BarData("右边店2", dataSeriesC, Color.rgb(155, 144, 206)))
    }

    private fun chartLabels() {
        chartLabels.add("桃子(Peach)")
        chartLabels.add("梨子(Pear)")
        chartLabels.add("香蕉 (Banana)")
        chartLabels.add("苹果")
        chartLabels.add("桔子")
    }

    override fun render(canvas: Canvas) {
        try {
            chart.render(canvas)
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // TODO Auto-generated method stub		
        super.onTouchEvent(event)
        if (event.action == MotionEvent.ACTION_UP) {
            triggerClick(event.x, event.y)
        }
        return true
    }

    //触发监听
    private fun triggerClick(x: Float, y: Float) {
        if (!chart.isValueSelectionEnabled) return
        val record = chart.getPositionRecord(x, y) ?: return
        val bData = BarDataset[record.dataID]
        val bValue = bData.dataSet[record.dataChildID]

        //在点击处显示tooltip
        mPaintToolTip.color = Color.WHITE
        chart.toolTip?.backgroundPaint?.color = Color.rgb(75, 202, 255)
        chart.toolTip?.borderPaint?.color = Color.RED
        chart.toolTip?.setCurrentXY(x, y)
        chart.toolTip?.addToolTip(
            " Current Value:" + java.lang.Float.toString(bValue), mPaintToolTip
        )
        chart.toolTip?.backgroundPaint?.alpha = 100
        this.invalidate()
    }
}